/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.Result;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.Area;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户Controller
 * @author ThinkGem
 * @version 2013-8-29
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/user")
public class UserController extends BaseController {

    @Autowired
    private OfficeService officeService;
	@Autowired
	private SystemService systemService;
	
	@ModelAttribute
	public User get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return systemService.getUser(id);
		}else{
			return new User();
		}
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = {"index"})
	public String index(User user, Model model) {
        return "modules/sys/userIndex";
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = {"list", ""})
	public String list(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAttribute("allRoles", systemService.findAllRole());

        user.getSqlMap().put("dsf", BaseService.dataScopeFilter(user.getCurrentUser(), "o", "", ""));
        List<User> list = systemService.findList(user);
        for(User temuser:list){
            temuser.setRemarks(User.DEL_FLAG_NORMAL.equals(temuser.getDelFlag())?"正常":"审核中");
        }

        List<Office> listOffice = officeService.findList(true);
        User temUser;
        for(Office office:listOffice){
            temUser = new User();
            temUser.setId(office.getId());
            temUser.setOffice(new Office(office.getParentId(), office.getName()));
			temUser.setPhoto(office.getName());
            temUser.setLoginFlag("display:none;");
            list.add(temUser);
        }

        model.addAttribute("list", list);
		return "modules/sys/userList";
	}
	
	@ResponseBody
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = {"listData"})
	public Page<User> listData(User user, HttpServletRequest request, HttpServletResponse response) {
        return systemService.findUser(new Page<User>(request, response), user);
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "form")
	public String form(User user, Model model) {
	    // 清除之前处理用户的缓存
        UserUtils.removeCache(UserUtils.getUser().getId()+"_CREATE_USER");

		if (user.getCompany()==null || user.getCompany().getId()==null){
			user.setCompany(UserUtils.getUser().getCompany());
		}
		if (user.getOffice()==null || user.getOffice().getId()==null){
			user.setOffice(UserUtils.getUser().getOffice());
		}
		model.addAttribute("user", user);
		model.addAttribute("allRoles", systemService.findAllRole());
		return "modules/sys/userForm";
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "save")
	public String save(User user, HttpServletRequest request, Model model) {
        this.mgrUserOffice(user, request);

        // 字典中配置默认密码
		user.setPassword(SystemService.entryptPassword(DictUtils.getDictValue("password","systemvalue","123456")));

		if (!beanValidator(model, user)){
			return form(user, model);
		}
		if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))){
			addMessage(model, "保存用户'" + user.getLoginName() + "'失败，帐号已存在");
			return form(user, model);
		}
		// 角色数据有效性验证，过滤不在授权内的角色
		List<Role> roleList = Lists.newArrayList();
		Role role = user.getRole();
		for (Role r : systemService.findAllRole()){
			if ((role.getId()).equals(r.getId())){
				roleList.add(r);
			}
		}
		user.setRoleList(roleList);

        if (!UserUtils.getSubject().isPermitted("sys:user:check")){
            user.setDelFlag(User.DEL_FLAG_AUDIT);
        }else{
            user.setCheckDate(new Date());
            user.setCheckBy(UserUtils.getUser());
            user.setDelFlag(User.DEL_FLAG_NORMAL);
        }
        UserUtils.putCache(UserUtils.getUser().getId()+"_CREATE_USER", user);
        return "modules/sys/userInfoConfirm";
    }

    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "formsave")
    public String formsave(Model model) {
        User user = (User)UserUtils.getCache(UserUtils.getUser().getId()+"_CREATE_USER");
        // 保存用户信息
        systemService.saveUser(user);

        // 清除当前用户缓存
        if (user.getLoginName().equals(UserUtils.getUser().getLoginName())){
            UserUtils.clearCache();
        }
        UserUtils.removeCache(UserUtils.getUser().getId()+"_CREATE_USER");
        model.addAttribute("user", user);
        model.addAttribute("password", DictUtils.getDictValue("password","systemvalue","123456"));
        return "modules/sys/userInfoConfirmTips";
    }

    private void mgrUserOffice(User user, HttpServletRequest request){
        boolean needCreateCompany = true;
        String companyId = request.getParameter("company.id");
        String companyName = request.getParameter("company.name");
        Office company = null;
        if(StringUtils.isNotEmpty(companyId)){
            company = officeService.get(companyId);
            if(company.getName().equals(companyName)){
                needCreateCompany = false;
            }
        }
        if(needCreateCompany){
            company = new Office();
            company.setName(companyName);
            company.setParent(officeService.get("1"));
            company.setType("1");
            company.setUseable(Global.YES);
            company.setArea(new Area("1"));
            company.setGrade("1");
            officeService.save(company);
        }
        boolean needCreateOffice = true;
        String officeId = request.getParameter("office.id");
        String officeName = request.getParameter("office.name");
        Office office = null;
        if(StringUtils.isNotEmpty(officeId)){
            office = officeService.get(officeId);
            if(office.getName().equals(officeName)){
                needCreateOffice = false;
            }
        }
        if(needCreateOffice){
            office = new Office();
            office.setName(officeName);
            office.setParent(company);
            office.setType("2");
            office.setUseable(Global.YES);
            office.setArea(new Area("1"));
            office.setGrade("2");
            officeService.save(office);
        }

        user.setCompany(company);
        user.setOffice(office);
    }

    @RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "delete")
	public String delete(User user, RedirectAttributes redirectAttributes) {
		if (UserUtils.getUser().getId().equals(user.getId())){
			addMessage(redirectAttributes, "删除用户失败, 不允许删除当前用户");
		}else if (User.isAdmin(user.getId())){
			addMessage(redirectAttributes, "删除用户失败, 不允许删除超级管理员用户");
		}else{
			systemService.deleteUser(user);
			addMessage(redirectAttributes, "删除用户成功");
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}
	
	/**
	 * 导出用户数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(User user, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "用户数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<User> page = systemService.findUser(new Page<User>(request, response, -1), user);
    		new ExportExcel("用户数据", User.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出用户失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
    }

	/**
	 * 导入用户数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/list?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<User> list = ei.getDataList(User.class);
			for (User user : list){
				try{
					if ("true".equals(checkLoginName("", user.getLoginName()))){
						user.setPassword(SystemService.entryptPassword("123456"));
						BeanValidators.validateWithException(validator, user);
						systemService.saveUser(user);
						successNum++;
					}else{
						failureMsg.append("<br/>登录名 "+user.getLoginName()+" 已存在; ");
						failureNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>登录名 "+user.getLoginName()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/>登录名 "+user.getLoginName()+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条用户，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条用户"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
    }
	
	/**
	 * 下载导入用户数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "用户数据导入模板.xlsx";
    		List<User> list = Lists.newArrayList(); list.add(UserUtils.getUser());
    		new ExportExcel("用户数据", User.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    /**
     * 重置用户密码
     * @param user
     * @param model
     * @return
     */
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "resetPassword")
    public String resetPassword(User user, Model model) {
        String newPassword = DictUtils.getDictValue("password", "systemvalue", "123456");
        systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
        model.addAttribute("message", "重置密码成功");
        model.addAttribute("user", user);

        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

	/**
	 * 验证登录名是否有效
	 * @param oldLoginName
	 * @param loginName
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "checkLoginName")
	public String checkLoginName(String oldLoginName, String loginName) {
        if (loginName !=null && loginName.equals(oldLoginName)) {
            return "true";
        } else if (loginName !=null && systemService.getUserByLoginName(loginName) == null) {
            return "true";
        }
        return "false";
	}

    /**
     * 验证 手机号码是否重复
     * @param userId
     * @param mobile
     * @return
     */
    @ResponseBody
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "checkMobile")
    public boolean checkMobile(String userId, String mobile){
        List<User> users = systemService.getUserByMobile(mobile);
        return null == users || users.isEmpty() || users.size() < 2 && users.get(0).getId().equals(userId);
    }

	/**
	 * 用户信息显示及保存
	 * @param user
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "info")
	public String info(User user, Model model) {
        User loginUser = UserUtils.getUser();
        if(null == user || StringUtils.isEmpty(user.getId())){
            model.addAttribute("user", loginUser);
            model.addAttribute("isSelf", true);
        }
        else{
            model.addAttribute("user", user);
            model.addAttribute("isSelf", loginUser.getId().equals(user.getId()));
        }

        model.addAttribute("Global", new Global());
		return "modules/sys/userInfo";
	}

	/**
	 * 返回用户信息
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "infoData")
	public User infoData() {
		return UserUtils.getUser();
	}
	
	/**
	 * 修改个人用户密码
	 * @param oldPassword
	 * @param newPassword
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "modifyPwd")
	public String modifyPwd(String oldPassword, String newPassword, Model model) {
		User user = UserUtils.getUser();
		if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)){
			if(Global.isDemoMode()){
				model.addAttribute("message", "演示模式，不允许操作！");
				return "modules/sys/userModifyPwd";
			}
			if (SystemService.validatePassword(oldPassword, user.getPassword())){
				systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
				model.addAttribute("message", "修改密码成功");
			}else{
				model.addAttribute("message", "修改密码失败，旧密码错误");
			}
		}
		model.addAttribute("user", user);
		return "modules/sys/userModifyPwd";
	}
	
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String officeId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<User> list = systemService.findUserByOfficeId(officeId);
		for (int i=0; i<list.size(); i++){
			User e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", "u_"+e.getId());
			map.put("pId", officeId);
			map.put("name", StringUtils.replace(e.getName(), " ", ""));
			mapList.add(map);
		}
		return mapList;
	}

    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "recheck")
    public String recheck(String userId, RedirectAttributes redirectAttributes){
        User user = new User(userId);
        user.setDelFlag(User.DEL_FLAG_AUDIT);
        Result result = systemService.check(user);
        addMessage(redirectAttributes, "已经重新提交审核!");
        return "redirect:" + adminPath + "/sys/user/info?id=" + userId;
    }

    @RequiresPermissions("sys:user:check")
    @RequestMapping(value = "check")
    public String check(String userId, String delFlag, RedirectAttributes redirectAttributes){
        User user = new User(userId);
        user.setDelFlag(delFlag);
        user.setCheckDate(new Date());
        user.setCheckBy(UserUtils.getUser());
        Result result = systemService.check(user);
        addMessage(redirectAttributes, result.getMsg());
        return "redirect:" + adminPath + "/sys/user/info?id=" + userId;
    }
}
